Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.11.0, we can simply call it Python3. Python 3.0 was released in 2008. and is interpreted language i.e it’s not compiled and the interpreter will check the code line by line. This article can be used to learn the very basics of Python programming language. So before moving on further.. let’s do the most popular ‘HelloWorld’ tradition 😛 and hence compare Python’s Syntax with C, C++, and Java ( I have taken these 3 because they are the most famous and mostly used languages).
# Python code for "Hello World"
# nothing else to type...see how simple is the syntax.
print("Hello World")
Hello World
Within IPython you have various way to access help:
?
-->Introduction and overview of IPython's features (this screen).object?
--> Details about 'object'.object??
--> More detailed, verbose information about 'object'.%quickref
--> Quick reference of all IPython specific syntax and magics.help
--> Access Python's own help system.In python there are 4 four types of variables: integer, float, string and date.
Note: To work with date or time variables, you would need datetime package
.
myNumber = 3
print(myNumber)
myNumber2 = 4.5
print(myNumber2)
myNumber ="helloworld"
print(myNumber)
from datetime import datetime, date, time
mydate= datetime(2023,1,14)
print(mydate)
3 4.5 helloworld 2023-01-14 00:00:00
Objects in Python typically have both attributes, other Python objects stored “inside” the object, and methods, functions associated with an object which can have access to the object’s internal data. Both of them are accessed via the syntax:
obj.attribute_name
or
using the function dir()
we can get all functions and methods of a class.
#dir(myNumber)
dir(myNumber)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
To check if two references refer to the same object, use the is
keyword. is not
is also perfectly valid if you want to check that two objects are not the same:
a= 4
b= a
c=3
print("a is b :", a is b)
print("b is not c :", b is not c)
a is b : True b is not c : True
Other binary operators are :
a + b
--> Add a and ba - b
--> Subtract b from aa * b
--> Multiply a by ba / b
--> Divide a by ba // b
--> Floor-divide a by b, dropping any fractional remaindera ** b
--> Raise a to the b powera & b
--> True if both a and b are True. For integers, take the bitwise AND.a | b
--> True if either a or b is True. For integers, take the bitwise OR.a ^ b
--> For booleans, True if a or b is True, but not both. For integers, take the bitwisea == b
--> True if a equals ba != b
--> True if a is not equal to ba <= b, a < b
--> True if a is less than (less than or equal) to ba > b, a >= b
--> True if a is greater than (greater than or equal) to bIn python indexing will start with 0.
a= [1,2,3,4,5,6] ## a list object
print("1st element :",a[0])
print("last element: ", a[5])
# To get length of use function len()
print("length of the list item 'a' is: ",len(a))
1st element : 1 last element: 6 length of the list item 'a' is: 6 1
x='Rajesh'
print(x)
Rajesh
y="Rajesh"
y
'Rajesh'
x='Rajesh's Notes'
x
File "C:\Users\User\AppData\Local\Temp\ipykernel_9548\2825554798.py", line 1 x='Rajesh's Notes' ^ SyntaxError: invalid syntax
x="Rajesh's Notes"
x
"Rajesh's Notes"
print(type(x))
<class 'str'>
He_said='He saaid,"How are you?"'
He_said
'He saaid,"How are you?"'
I_replied= """I replied, 'I am good...
Tell me about your self..'"""
print(I_replied)
I replied, 'I am good... Tell me about your self..'
message= "Hello World"
print(message)
Hello World
print("length of the string variable is:",len(message))
print("1'st element of the message variable:",message[0])
print("last element of the message variable:",message[10])
print(message[11])
length of the string variable is: 11 1'st element of the message variable: H last element of the message variable: d
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_9548\3776183124.py in <module> 5 print("last element of the message variable:",message[10]) 6 ----> 7 print(message[11]) IndexError: string index out of range
print(message[0:10])
print(message[0:11])
print(message[:11]) # return full length string
print(message[:10]) # return elements of the string,
# except without including the last element
print(message[0:5])
print(message[6:])
Hello Worl Hello World Hello World Hello Worl Hello World
#*** That means indexing will start from 0. So, if
#*** if there will be 10 elements, then x[9] will give the 10th
#*** element of 'x'.
print(message.lower()) # to lower case
print(message.upper()) # to upper case
hello world HELLO WORLD
print(message.count('l'))
print(message.count("Hello"))
print(message.count("m"))
print(message.find("Hello"))
print(message.find("l"))
3 1 0 0 2
##--Replacing values--##
newmessage= message.replace("World","Sir")
print(newmessage)
print(message)
Hello Sir Hello World
##-- Concatinating strings
x="Hello"
y="World"
print(x+y)
print(x+" "+y)
HelloWorld Hello World
## to get more help for string:
# print(help(str))
# Similarly to get help on integer, type: print(help(int))
Python have 4 types of built-in Data Structures namely List, Dictionary, Tuple, and Set.
The list type is probably the most commonly used collection type in Python.Despite its name, a list is more like an array in other languages.Lists are mutable, so you can change the values in a list. A list can be created by enclosing values, separated by commas, in square brackets:
int_list = [3, 2, 1, 4]
string_list = ['abc', 'defghi']
empty_list = []
mixed_list = [1, 'abc', True, 2.34, None]
nested_list = [['a', 'b', 'c'], [1, 2, 3]]
subjects= ["Bengali","English","Math","Physics","Chemistry","Statistics","Comp.Sc"]
print("type of 'int_list':",type(int_list),
"\n type of 'string_list':",type(string_list),
"\n type of 'empty_list':",type(empty_list),
"\n type of 'mixed_list':",type(mixed_list),
"\n type of 'nested_list':",type(nested_list),
"\n type of 'subjects':",type(subjects))
type of 'int_list': <class 'list'> type of 'string_list': <class 'list'> type of 'empty_list': <class 'list'> type of 'mixed_list': <class 'list'> type of 'nested_list': <class 'list'> type of 'subjects': <class 'list'>
print(len(subjects),len(empty_list),len(int_list))
print("subjects[0]:",
subjects[0],
"\n and its length:",
len(subjects[0]))
7 0 4 subjects[0]: Bengali and its length: 7
# Lists in Python are zero-indexed meaning that the first element in the
# list is at index 0, the second element is at index 1 and so on.
print(mixed_list[:4])
print(mixed_list[3:])
[1, 'abc', True, 2.34] [2.34, None]
# Indices can also be negative which means counting from the end
# of the list (-1 being the index of the last element).
print(string_list[-1])
print(string_list[-0])
print(subjects[-2:])
print(subjects[:-2])
defghi abc ['Statistics', 'Comp.Sc'] ['Bengali', 'English', 'Math', 'Physics', 'Chemistry']
##-- Get the index of an element of a list
print(subjects.index("Math"))
2
# Lists are mutable, so we can change the values in a list:
subjects[0] = 'Hindi';print(subjects)
['Hindi', 'English', 'Math', 'Physics', 'Chemistry', 'Statistics', 'Comp.Sc']
# Append object to end of list
subjects.append("Bengali");print(subjects)
['Hindi', 'English', 'Math', 'Physics', 'Chemistry', 'Statistics', 'Comp.Sc', 'Bengali']
#Add a new element to list at a specific index.
subjects.insert(1, "Urdu");print(subjects)
['Hindi', 'Urdu', 'English', 'Math', 'Physics', 'Chemistry', 'Statistics', 'Comp.Sc', 'Bengali']
# Remove the first occurrence of a value:
subjects.remove("English");print(subjects)
# Reverse the list
subjects.reverse();print(subjects)
# or
#subjects[::-1]
['Bengali', 'Comp.Sc', 'Statistics', 'Chemistry', 'Physics', 'Math', 'English', 'Urdu', 'Hindi']
# Extracting values from nested list object
print(nested_list[0])
['a', 'b', 'c']
print(nested_list[0][1])
b
# Sorting
print(sorted(int_list))
print(sorted(subjects))
[1, 2, 3, 4] ['Bengali', 'Chemistry', 'Comp.Sc', 'English', 'Hindi', 'Math', 'Physics', 'Statistics', 'Urdu']
# Remove and return item at index
int_list.pop(1);print(int_list)
[3, 1, 4]
# pop() will always remove the last item of a list
int_list.pop();print(int_list)
[3, 1]
# to join all elements of a list with some commas and to store as a single string character
print(subjects)
subjects_str= ', '.join(subjects);print(subjects_str)
print(type(subjects_str))
print(type(subjects))
['Bengali', 'Comp.Sc', 'Statistics', 'Chemistry', 'Physics', 'Math', 'English', 'Urdu', 'Hindi'] Bengali, Comp.Sc, Statistics, Chemistry, Physics, Math, English, Urdu, Hindi <class 'str'> <class 'list'>
# to split a string and convet it into a list:
new_subjects_list= subjects_str.split(', ')
print(new_subjects_list)
print(type(new_subjects_list))
['Bengali', 'Comp.Sc', 'Statistics', 'Chemistry', 'Physics', 'Math', 'English', 'Urdu', 'Hindi'] <class 'list'>
# entering values in an empty list
empty_list.append("Arnab");print(empty_list)
['Arnab']
List Methods
Method | Description | Syntaxt | |
---|---|---|---|
append() | Adds an element at the end of the list | list.append(elmnt) | |
clear() | Removes all the elements from the list | list.clear() | |
copy() | Returns a copy of the list | list.copy() | |
count() | Returns the number of elements with the specified value | list.count(value) | |
extend() | Add the elements of a list (or any iterable), to the end of the current list | list.extend(iterable) | |
index() | Returns the index of the first element with the specified value | list.index(elmnt) | |
insert() | Adds an element at the specified position | list.insert(pos,elmnt) | |
pop() | Removes the element at the specified position | list.pop(pos) | |
remove() | Removes the item with the specified value | list.remove(elmnt) | |
reverse() | Reverses the order of the list | list.reverse() | |
sort() | Sorts the list | list.sort(reverse=T$ | $F,key=myFunc) |
A tuple is similar to a list except that it is 'fixed-length' and 'immutable'.So the values in the tuple cannot be changed nor the values be added to or removed from the tuple.
Tuples are commonly used for small collections of values that will not need to change, such as an IP address and port.
tuple_1= ('History','Math','Physics','Statistics')
tuple_2= (1,2,3,4,4,6)
print("Type of 'tuple_1' is : ",type(tuple_1),
"\nType of 'tuple_2' is : ",type(tuple_1))
Type of 'tuple_1' is : <class 'tuple'> Type of 'tuple_2' is : <class 'tuple'>
tuple_1[0]
'History'
tuple_1[0]='Bengali' ##-- We cannot change values inside a tuple
tuple_1.append('Urdu')##-- We cannot append values inside a tuple
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_9548\3320454280.py in <module> ----> 1 tuple_1[0]='Bengali' ##-- We cannot change values inside a tuple 2 tuple_1.append('Urdu') TypeError: 'tuple' object does not support item assignment
Same Kind of operations can be done with tuples just like list, except appending or changing values.
tuple_2.count(4)
2
List Methods
Method | Description | Syntaxt |
---|---|---|
count() | Returns the number of elements with the specified value | list.count(value) |
index() | Returns the index of the first element with the specified value | list.index(elmnt) |
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered, changeable and do not allow duplicates.
Note(*): As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
Dictionaries are written with curly brackets {}
, and have keys and values:
empty_dict = {}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(empty_dict))
print(type(thisdict))
<class 'dict'> <class 'dict'>
Elements can be accessed and inserted or set using the same syntax as accessing elements of a list or tuple:
thisdict["brand"]
'Ford'
When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.
Unordered means that the items does not have a defined order, you cannot refer to an item by using an index.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
print(len(thisdict)) ##-- Length of a Dictionary
3
Dictionary Items - Data Types
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(type(thisdict))
print(type(thisdict["colors"]))
print(type(thisdict["year"]))
<class 'dict'> <class 'list'> <class 'int'>
Using the dict()
method to make a dictionary:
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)
{'name': 'John', 'age': 36, 'country': 'Norway'}
Get Keys
The keys()
method will return a list of all the keys in the dictionary.
x = thisdict.keys()
x
dict_keys(['name', 'age', 'country'])
Adding a new item in a Dictionary
Add a new item to the original dictionary, and see that the keys list gets updated as well:
dict_2= {"Name":'Rajesh',
"Age": 25,
"Gender": 'M',
"Residence": 'Kolkata'}
print(dict_2.keys())
dict_keys(['Name', 'Age', 'Gender', 'Residence'])
dict_2["City"]='New Barrackpur'
print(dict_2.keys())
dict_keys(['Name', 'Age', 'Gender', 'Residence', 'City'])
Nested Dictionary
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
## or if we want to add three dictionaries into a new dictionary:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily)
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}} {'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
Removing Items
The pop()
method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
{'brand': 'Ford', 'year': 1964}
The del
keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
{'brand': 'Ford', 'year': 1964}
Method | Description |
---|---|
clear() | Removes all the elements from the dictionary |
copy() | Returns a copy of the dictionary |
fromkeys() | Returns a dictionary with the specified keys and value |
get() | Returns the value of the specified key |
items() | Returns a list containing a tuple for each key value pair |
keys() | Returns a list containing the dictionary's keys |
pop() | Removes the element with the specified key |
popitem() | Removes the last inserted key-value pair |
setdefault() | Returns the value of the specified key. If the key does not exist: insert the key, with the specified value |
update() | Updates the dictionary with the specified key-value pairs |
values() | Returns a list of all the values in the dictionary |
A set is an unordered collection of unique elements. You can think of them like dictionaries, but keys only, no values. A set can be created in two ways: via the set function or using a set literal with curly braces{}:
x= set([2, 2, 2, 1, 3, 3])
y= {1,2,3,4,5}
print(x)
print(y)
{1, 2, 3} {1, 2, 3, 4, 5}
print(type(x))
print(type(y))
<class 'set'> <class 'set'>
Note: Set items are unchangeable, but you can remove items and add new items.
Unordered means that the items in a set do not have a defined order. Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
Set items are unchangeable, meaning that we cannot change the items after the set has been created. Once a set is created, you cannot change its items, but you can remove items and add new items.
Sets support mathematical set operations like union, intersection, difference, and symmetric difference.
Commonly used Python Set Operations
Function | Alternate | Syntax Description | |
---|---|---|---|
a.add(x) | N/A | Add element x to the set a | |
a.remove(x) | N/A | Remove element x from the set a | |
a.union(b) | a $ | $ b | All of the unique elements in a and b. |
a.intersection(b) | a & b | All of the elements in both a and b. | |
a.difference(b) | a - b | The elements in a that are not in b. | |
a.symmetric_difference(b) | a ^ b | All of the elements in a or b but not both. | |
a.issubset(b) | N/A | True if the elements of a are all contained in b. | |
a.issuperset(b) | N/A | True if the elements of b are all contained in a. | |
a.isdisjoint(b) | N/A | True if a and b have no elements in common. | |
a.update() | N/A | Update the set with the union of this set and others |
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
{'cherry', 'apple', 'banana'}
So, for an example, suppose we have a list object with multiple repeated values and if we want to extract the unique values from it then we can use set :
x= [1,2,3,2,3,4,5,4,6,7,6,5,8] ##--- Our Array ---##
x_unique= list(set(x))
print(x_unique) ##---- Unique Value ---##
[1, 2, 3, 4, 5, 6, 7, 8]
Python supports the usual logical conditions from mathematics:
a == b
a != b
a < b
a <= b
a > b
a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
An "if statement" is written by using the if
keyword.
a = 33
b = 200
if b > a:
print("b is greater than a")
b is greater than a
*Note that like C,C++ or other programming languages, here we dont use {}
. Similarly for loops.
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.
a = 33
b = 200
if b > a:
print("b is greater than a")
File "C:\Users\User\AppData\Local\Temp\ipykernel_9548\1111622982.py", line 4 print("b is greater than a") ^ IndentationError: expected an indented block
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
a and b are equal
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
a is greater than b
Short Hand If
if a > b: print("a is greater than b")
a is greater than b
Short Hand If ... Else
If we have only one statement to execute, one for if, and one for else, we can put it all on the same line:
a = 2
b = 330
print("A") if a > b else print("B")
B
We can also have multiple else statements on the same line:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
=
The And
keyword is a logical operator, and is used to combine conditional statements:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Both conditions are True
The or keyword is a logical operator, and is used to combine conditional statements:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
At least one of the conditions is True
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Above ten, and also above 20!
if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.
a = 33
b = 200
if b > a:
pass
## Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
1 2 3 4 5
The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1.
With the break statement we can stop the loop even if the while condition is true:
## Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
1 2 3
With the continue statement we can stop the current iteration, and continue with the next:
## Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
1 2 4 5 6
With the else statement we can run a block of code once when the condition no longer is true:
## Print a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
1 2 3 4 5 i is no longer less than 6
# Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
apple banana cherry
Looping Through a String
# Loop through the letters in the word "Rajesh":
for x in "Rajesh":
print(x)
R a j e s h
## Exit the loop when x is "Arnab":
friends = ["Rahesh", "Arnab", "Mainak"]
for x in friends:
print(x)
if x == "Arnab":
break
Rahesh Arnab
## Exit the loop when x is "banana", but this time the break comes before the print:
friends = ["Rahesh", "Arnab", "Mainak"]
for x in friends:
if x == "Arnab":
break
print(x)
Rahesh
friends = ["Rahesh", "Arnab", "Mainak"]
for x in friends:
if x == "Arnab":
continue
print(x)
Rahesh Mainak
To loop through a set of code a specified number of times, we can use the range()
function.
The range()
function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
for x in range(6):
print(x)
0 1 2 3 4 5
## Summation of a vector
x=[1,2,3,4,5]
sum=0
for i in range(len(x)):
sum= sum+x[i]
print("Sum of x is:",sum)
Sum of x is: 15
The range()
function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3)
:
## Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
2 5 8 11 14 17 20 23 26 29
The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
## Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
0 1 2 3 4 5 Finally finished!
## Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
0 1 2
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
## Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
red apple red banana red cherry big apple big banana big cherry tasty apple tasty banana tasty cherry
for x in [0, 1, 2]:
pass
In Python a function is defined using the def
keyword:
def my_function():
print("Hello from a function")
def my_function():
print("Hello from a function")
my_function()
Hello from a function
# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print('Sum: ',sum)
# function call with two values
add_numbers(5, 4)
Sum: 9
A Python function may or may not return a value. If we want our function to return some value to a function call, we use the return
statement. For example,
# function definition
def find_square(num):
result = num * num
return result
# function call
square = find_square(3)
print('Square:',square)
Square: 9
## creating function for Average.
def mean(x):
sum=0
for i in range(len(x)):
sum= sum+x[i]
mean= sum/len(x)
return(mean)
x=[1,2,3,4,5]
Average= int(mean(x))
print("The Average of x is:",Average)
The Average of x is: 3
## Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
15
Lambda functions can take any number of arguments:
## Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
30
The power of lambda is better shown when we use them as an anonymous function inside another function.
Say we have a function definition that takes one argument, and that argument will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
# Use that function definition to make a function that always doubles the number we send in:
mydoubler = myfunc(2)
print(mydoubler(11))
22
## Or, use the same function definition to make a function that always triples the number you send in:
mytripler = myfunc(3)
print(mytripler(11))
33
## Or, use the same function definition to make both functions, in the same program:
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
22 33
Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.
The min()
and max()
functions can be used to find the lowest or highest value in an iterable:
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
5 25
The abs()
function returns the absolute (positive) value of the specified number:
x = abs(-7.25)
print(x)
7.25
The pow(x, y)
function returns the value of x to the power of y $(x^y)$.
x = pow(4, 3)
print(x)
64
Python has also a built-in module called math
, which extends the list
of mathematical functions.
To use it, you must import the math module:
import math
When we have imported the math module, we can start using methods and constants of the module.
The math.sqrt()
method for example, returns the square root of a number:
import math
x = math.sqrt(64)
print(x)
8.0
Math Methods
Method | Description |
---|---|
math.acos() | Returns the arc cosine of a number |
math.acosh() | Returns the inverse hyperbolic cosine of a number |
math.asin() | Returns the arc sine of a number |
math.asinh() | Returns the inverse hyperbolic sine of a number |
math.atan() | Returns the arc tangent of a number in radians |
math.atan2() | Returns the arc tangent of y/x in radians |
math.atanh() | Returns the inverse hyperbolic tangent of a number |
math.ceil() | Rounds a number up to the nearest integer |
math.comb() | Returns the number of ways to choose k items from n items without repetition and order |
math.copysign() | Returns a float consisting of the value of the first parameter and the sign of the second parameter |
math.cos() | Returns the cosine of a number |
math.cosh() | Returns the hyperbolic cosine of a number |
math.degrees() | Converts an angle from radians to degrees |
math.dist() | Returns the Euclidean distance between two points (p and q),where p and q are the coordinates |
math.erf() | Returns the error function of a number |
math.erfc() | Returns the complementary error function of a number |
math.exp() | Returns E raised to the power of x |
math.expm1() | Returns Ex - 1 |
math.fabs() | Returns the absolute value of a number |
math.factorial() | Returns the factorial of a number |
math.floor() | Rounds a number down to the nearest integer |
math.fmod() | Returns the remainder of x/y |
math.frexp() | Returns the mantissa and the exponent, of a specified number |
math.fsum() | Returns the sum of all items in any iterable (tuples, arrays, lists, etc.) |
math.gamma() | Returns the gamma function at x |
math.gcd() | Returns the greatest common divisor of two integers |
math.hypot() | Returns the Euclidean norm |
math.isclose() | Checks whether two values are close to each other, or not |
math.isfinite() | Checks whether a number is finite or not |
math.isinf() | Checks whether a number is infinite or not |
math.isnan() | Checks whether a value is NaN (not a number) or not |
math.isqrt() | Rounds a square root number downwards to the nearest integer |
math.ldexp() | Returns the inverse of math.frexp() which is x $*$ (2$**$i) of the given numbers x and i |
math.lgamma() | Returns the log gamma value of x |
math.log() | Returns the natural logarithm of a number, or the logarithm of number to base |
math.log10() | Returns the base-10 logarithm of x |
math.log1p() | Returns the natural logarithm of 1+x |
math.log2() | Returns the base-2 logarithm of x |
math.perm() | Returns the number of ways to choose k items from n items with order and without repetition |
math.pow() | Returns the value of x to the power of y |
math.prod() | Returns the product of all the elements in an iterable |
math.radians() | Converts a degree value into radians |
math.remainder() | Returns the closest value that can make numerator completely divisible by the denominator |
math.sin() | Returns the sine of a number |
math.sinh() | Returns the hyperbolic sine of a number |
math.sqrt() | Returns the square root of a number |
math.tan() | Returns the tangent of a number |
math.tanh() | Returns the hyperbolic tangent of a number |
math.trunc() | Returns the truncated integer parts of a number |
Math Constants
Constant | Description |
---|---|
math.e | Returns Euler's number (2.7182...) |
math.inf | Returns a floating-point positive infinity |
math.nan | Returns a floating-point NaN (Not a Number) value |
math.pi | Returns PI (3.1415...) |
math.tau | Returns tau (6.2831...) |
PIP is a package manager for Python packages, or modules if you like.
Navigate your command line to the location of Python's script directory, and type the following:
Example Check PIP version:
Downloading a package is very easy.
Open the command line interface and tell PIP to download the package you want.
Navigate your command line to the location of Python's script directory, and type the following: